<template>
  <Component
    ref="refComponent"
    v-bind="{
      ...attrs,
      ...pickOwnForBasicComponent(mappingProps, Component.props, attrs),
    }"
    :class="['t-banner', styles.module, 'no-outline']"
    v-show="mappingProps.visible"
    tabindex="-1"
  >
    <template v-slot:default>
      <div
        v-if="mappingProps.content && !mappingProps.pageModel"
        ref="bannerContainer"
        :class="{ 'banner-container': mappingProps.scroll }"
        :title="mappingProps.overWidth ? mappingProps.content : ''"
      >
        <div
          ref="bannerRef"
          :class="{
            'over-wrap': !mappingProps.overWidth,
            'over-width': mappingProps.overWidth,
            'banner-scroll': mappingProps.scroll,
          }"
          :style="scrollStyle"
          v-html="mappingProps.content"
        >
        </div>
      </div>
      <div
        v-if="mappingProps.content && mappingProps.pageModel"
        ref="bannerContainer"
        :class="{ 'banner-container': mappingProps.scroll }"
        :title="mappingProps.overWidth ? content : ''"
      >
        <div
          ref="bannerRef"
          :class="{
            'over-wrap': !mappingProps.overWidth,
            'over-width': mappingProps.overWidth,
            'banner-scroll': mappingProps.scroll,
          }"
          :style="scrollStyle"
        >
          <q-carousel
            ref="bannerCarousel"
            v-model="slide"
            vertical
            transition-prev="slide-down"
            transition-next="slide-up"
            animated
            control-color="white"
            height="22px"
            style="background-color: rgba(0, 0, 0, 0)"
          >
            <q-carousel-slide
              v-for="(item, index) in content"
              :key="'banner-slide' + index"
              :name="item.Code"
              class="banner-slide"
            >
              <div
                ref="bannerRef"
                :class="{
                  'over-wrap': !mappingProps.overWidth,
                  'over-width': mappingProps.overWidth,
                  'banner-scroll': mappingProps.scroll,
                }"
                :style="scrollStyle"
                v-html="item.Name"
              >
              </div>
            </q-carousel-slide>
          </q-carousel>
        </div>
      </div>
      <slot name="default" v-else></slot>
    </template>

    <template v-slot:avatar>
      <Icon v-if="icon" :name="icon" :color="mappingProps.iconColor" />
      <slot v-else name="avatar"></slot>
    </template>

    <template v-slot:action>
      <Button
        v-if="mappingProps.content && mappingProps.pageModel"
        class="tr-banner-button"
        @click="prevSlide"
        :label="'上一条'"
        :disable="slide == '1'"
        :tabIndex="attrs.tabIndex == undefined ? -1 : attrs.tabIndex"
      ></Button>
      <Button
        v-if="mappingProps.content && mappingProps.pageModel"
        class="tr-banner-button"
        @click="nextSlide"
        :label="'下一条'"
        :disable="slide == '2'"
        :tabIndex="attrs.tabIndex == undefined ? -1 : attrs.tabIndex"
      ></Button>

      <Button
        class="tr-banner-button"
        @click="btnClick(item)"
        v-if="mappingProps.actions && mappingProps.actions.length > 0"
        v-for="(item, key, index) in mappingProps.actions"
        :key="index"
        :label="item.showLabel ? '' : item.label"
        :icon="item.icon"
        :tabIndex="attrs.tabIndex == undefined ? -1 : attrs.tabIndex"
        :color="item.color ?? ''"
      />

      <slot v-else name="action"></slot>
    </template>
  </Component>
</template>
<script>
import Component from '@teld/q-components/Banner';
import useMappingProps from 't/common/hooks/useMappingProps';
import {
  commonProps,
  fixNameSpace,
  pickOwnForBasicComponent,
} from 't/common/utils';
import { defineComponent, onBeforeUnmount, onMounted, ref, watch } from 'vue';
import Button from '../button';
import Icon from '../icon';
import styles from './index.module.scss';
import './index.scss';

export * from '@teld/q-components/Banner';

export default defineComponent({
  name: fixNameSpace(Component.name),
  props: {
    ...commonProps,
    ...Component.props,
    content: {
      type: [String, Array],
      default() {
        return '';
      },
    },
    pageModel: {
      type: Boolean,
      default() {
        return false;
      },
    },
    icon: {
      type: String,
      default() {
        return '';
      },
    },
    iconColor: {
      type: String,
      default() {
        return 'var(--t-color)';
      },
    },
    actions: {
      type: Array,
      default() {
        return [];
      },
    },
    scroll: {
      type: Boolean,
      default() {
        return false;
      },
    },
    overWidth: {
      type: Boolean,
      default() {
        return false;
      },
    },
    duration: {
      type: Number,
    },
  },
  components: { Component, Button, Icon },
  emits: ['banner-btn-click'],

  setup(props, { attrs, emit, expose, slots }) {
    const refComponent = ref();
    const bannerCarousel = ref();
    const [mappingProps, mappingExpose] = useMappingProps(props);
    const bannerRef = ref();
    const bannerContainer = ref();
    const content = ref([
      { Code: '1', Name: '1' },
      { Code: '2', Name: '2' },
    ]);
    const slide = ref('1');

    let scrollDuration = ref(10);
    let scrollStyle = ref('');
    if (!mappingProps.iconColor) {
      mappingProps.iconColor = 'var(--t-color)';
    }
    // if (mappingProps.pageModel) {
    //   content = mappingProps.content[0];
    // }
    expose(mappingExpose);
    //国际化处理
    const i18nMethod = () => {
      mappingProps.actions.forEach(element => {
        element.code = element.label;
      });
      if (!window.Funcs) {
        return;
      }
      for (let i of mappingProps.actions) {
        if (i.hasOwnProperty('ValueInfo_label')) {
          i.label = Funcs.GetTerms(i.ValueInfo_label, i.label);
        }
      }
    };
    i18nMethod();
    watch(
      () => {
        return [
          mappingProps.scroll,
          mappingProps.content,
          mappingProps.duration,
        ];
      },
      () => {
        if (mappingProps.scroll) {
          scrollMethod();
        } else {
          scrollMethodDelay();
        }
      },
    );
    watch(
      () => {
        return mappingProps.actions;
      },
      (newVal, oldVal) => {
        if (JSON.stringify(newVal) != JSON.stringify(oldVal)) {
          i18nMethod();
        }
      },
    );
    onMounted(() => {
      if (mappingProps.scroll) {
        scrollMethod();
      }
    });
    onBeforeUnmount(() => {
      scrollMethodDelay();
    });

    const btnClick = item => {
      emit('banner-btn-click', item);
    };
    const nextSlide = () => {
      bannerCarousel.value.next();
    };
    const prevSlide = () => {
      bannerCarousel.value.previous();
    };
    const scrollMethod = () => {
      updateScrollDuration();
      let paddingValue = bannerContainer.value.offsetWidth;
      scrollStyle.value = `padding-left:${paddingValue}px;animation-duration: ${scrollDuration.value}s `;
      window.addEventListener('resize', updateScrollDuration);
    };
    const scrollMethodDelay = () => {
      window.removeEventListener('resize', updateScrollDuration);
      scrollStyle.value = ``;
    };
    const updateScrollDuration = () => {
      // const bannerWidth = bannerRef.value.offsetWidth;
      const containerWidth = bannerRef.value.parentElement.offsetWidth;
      const duration = containerWidth / 100; // 调整滚动速度，适应实际情况
      scrollDuration.value = mappingProps.duration ?? duration;
    };

    return {
      scrollStyle,
      bannerContainer,
      bannerRef,
      scrollDuration,
      updateScrollDuration,
      btnClick,
      attrs,
      styles,
      slots,
      refComponent,
      bannerCarousel,
      mappingProps,
      Component,
      pickOwnForBasicComponent,
      slide,
      content,
      nextSlide,
      prevSlide
    };
  },
});
</script>
<style lang="scss">
.banner-container {
  overflow: hidden;
  white-space: nowrap;
}
.over-width {
  white-space: nowrap; /* 防止文本换行 */
  overflow: hidden; /* 隐藏溢出部分 */
  text-overflow: ellipsis; /* 显示省略号 */
  // max-width: 100%; /* 可根据需要设置最大宽度 */
}
.banner-scroll {
  // width: 100%;
  display: inline-block;
  // animation: scroll 10s linear infinite; /* 默认动画，避免未挂载前的初始状态 */
  animation: scroll linear infinite both;
}
.banner-slide {
  padding: 0;
}
@keyframes scroll {
  100% {
    transform: translate3d(-100%, 0, 0);
  }
  // to {
  //   transform: translateX(-100%);
  // }
}
</style>
